<?php
/**
 * Created by PhpStorm.
 * User: CCJK
 * Date: 2018/4/19
 * Time: 15:32
 * 创建一个自定义的命令行命令
 * 在命令行执行 php bin/console app:create-users
 */

namespace AppBundle\Command;


use AppBundle\Entity\Product;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;

class CreateProductCommand extends ContainerAwareCommand
{
    protected function configure()
    {
        $this
            // the name of the command (the part after "bin/console")
            // 命令的名字（"bin/console" 后面的部分）
            ->setName('app:create-product')
            ->addArgument("name",InputArgument::REQUIRED,"产品名字")
            ->addArgument("price",InputArgument::REQUIRED,"产品价格")
            ->addArgument("desc",InputArgument::REQUIRED,"产品描述")
            // the short description shown while running "php bin/console list"
            // 运行 "php bin/console list" 时的简短描述
            ->setDescription('创建一个产品')
            // the full command description shown when running the command with
            // the "--help" option
            // 运行命令时使用 "--help" 选项时的完整命令描述
            ->setHelp("创建一个产品");
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $name = $input->getArgument("name");
        $price = $input->getArgument("price");
        $desc = $input->getArgument("desc");
        if(!is_numeric($price)){
            $output->writeln('price must be number');
            $output->writeln('php bin/console pc 12000 "pc value 12000"');
            return;
        }


        $manager=$this->getContainer()->get("doctrine.orm.entity_manager");
        $product = new Product();
        $product->setName($name);
        $product->setPrice($price);
        $product->setDescription($desc);
       // $em = $this->getDoctrine()->getManager();
        // tells Doctrine you want to (eventually) save the Product (no queries yet)
        // 告诉Doctrine你希望（最终）存储Product对象（还没有语句执行）
        $manager->persist($product);
        // actually executes the queries (i.e. the INSERT query)
        // 真正执行语句（如，INSERT 查询）
        $manager->flush();
        $output->writeln($product);
//         outputs multiple lines to the console (adding "\n" at the end of each line)
//         输出多行到控制台（在每一行的末尾添加 "\n"）

//        $output->writeln([
//            'User Creator',
//            '============',
//            '',
//        ]);
//
//        // outputs a message followed by a "\n"
//        $output->writeln('Whoa!');
//        // outputs a message without adding a "\n" at the end of the line
//        $output->write('You are about to ');
    }
}